import BasePlugin from './BasePlugin';
import * as fabricModule from 'fabric';
const fabric = fabricModule.fabric || fabricModule;

/**
 * 标尺插件 - 处理画布标尺和参考线
 */
export default class RulerPlugin extends BasePlugin {
    constructor() {
        super();
        this.rulerHeight = 20;
        this.rulerWidth = 20;
        this.rulerColor = '#f0f0f0';
        this.rulerBorderColor = '#d0d0d0';
        this.rulerTextColor = '#666666';
        this.rulerFontSize = 10;
        this.rulerInterval = 10;
        this.showRuler = false;
        this.showGuides = true;
        this.guides = {
            horizontal: [],
            vertical: []
        };
        this.rulers = {
            horizontal: null,
            vertical: null
        };
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
        this._createRulers();
        this._setupGuideEvents();
    }

    /**
     * 显示标尺
     */
    show() {
        if (!this.isEnabled() || !this.canvas) return;

        this.showRuler = true;
        this._drawRulers();
        this.canvas.renderAll();
    }

    /**
     * 隐藏标尺
     */
    hide() {
        if (!this.isEnabled() || !this.canvas) return;

        this.showRuler = false;
        this._clearRulers();
        this.canvas.renderAll();
    }

    /**
     * 切换标尺显示状态
     */
    toggle() {
        if (this.showRuler) {
            this.hide();
        } else {
            this.show();
        }
    }

    /**
     * 显示参考线
     */
    showGuides() {
        if (!this.isEnabled() || !this.canvas) return;
        this.showGuides = true;
        this._drawGuides();
    }

    /**
     * 隐藏参考线
     */
    hideGuides() {
        if (!this.isEnabled() || !this.canvas) return;
        this.showGuides = false;
        this._clearGuides();
    }

    /**
     * 添加水平参考线
     */
    addHorizontalGuide(y) {
        if (!this.isEnabled() || !this.canvas) return;

        const guide = new fabric.Line([0, y, this.canvas.width, y], {
            stroke: '#00a8ff',
            strokeWidth: 1,
            selectable: true,
            lockMovementX: true,
            excludeFromExport: true,
            hasControls: false,
            hasBorders: false,
            originX: 'center',
            originY: 'center'
        });

        this.guides.horizontal.push(guide);
        this.canvas.add(guide);
        this.canvas.renderAll();
    }

    /**
     * 添加垂直参考线
     */
    addVerticalGuide(x) {
        if (!this.isEnabled() || !this.canvas) return;

        const guide = new fabric.Line([x, 0, x, this.canvas.height], {
            stroke: '#00a8ff',
            strokeWidth: 1,
            selectable: true,
            lockMovementY: true,
            excludeFromExport: true,
            hasControls: false,
            hasBorders: false,
            originX: 'center',
            originY: 'center'
        });

        this.guides.vertical.push(guide);
        this.canvas.add(guide);
        this.canvas.renderAll();
    }

    /**
     * 清除所有参考线
     */
    clearGuides() {
        if (!this.isEnabled() || !this.canvas) return;

        [...this.guides.horizontal, ...this.guides.vertical].forEach(guide => {
            this.canvas.remove(guide);
        });

        this.guides = {
            horizontal: [],
            vertical: []
        };

        this.canvas.renderAll();
    }

    /**
     * 创建标尺
     */
    _createRulers() {
        if (!this.canvas) return;

        // 创建水平标尺
        this.rulers.horizontal = new fabric.Rect({
            left: this.rulerWidth,
            top: 0,
            width: this.canvas.width,
            height: this.rulerHeight,
            fill: this.rulerColor,
            stroke: this.rulerBorderColor,
            strokeWidth: 1,
            selectable: false,
            evented: false,
            excludeFromExport: true
        });

        // 创建垂直标尺
        this.rulers.vertical = new fabric.Rect({
            left: 0,
            top: this.rulerHeight,
            width: this.rulerWidth,
            height: this.canvas.height,
            fill: this.rulerColor,
            stroke: this.rulerBorderColor,
            strokeWidth: 1,
            selectable: false,
            evented: false,
            excludeFromExport: true
        });

        // 创建标尺刻度
        this._createRulerMarks();
    }

    /**
     * 创建标尺刻度
     */
    _createRulerMarks() {
        if (!this.canvas) return;

        // 创建水平标尺刻度
        for (let i = 0; i <= this.canvas.width; i += this.rulerInterval) {
            const mark = new fabric.Line([i + this.rulerWidth, 0, i + this.rulerWidth, this.rulerHeight / 2], {
                stroke: this.rulerBorderColor,
                strokeWidth: 1,
                selectable: false,
                evented: false,
                excludeFromExport: true
            });

            if (i % 50 === 0) {
                mark.set({
                    strokeWidth: 2,
                    height: this.rulerHeight
                });

                const text = new fabric.Text(i.toString(), {
                    left: i + this.rulerWidth + 2,
                    top: 2,
                    fontSize: this.rulerFontSize,
                    fill: this.rulerTextColor,
                    selectable: false,
                    evented: false,
                    excludeFromExport: true
                });

                this.canvas.add(text);
            }

            this.canvas.add(mark);
        }

        // 创建垂直标尺刻度
        for (let i = 0; i <= this.canvas.height; i += this.rulerInterval) {
            const mark = new fabric.Line([0, i + this.rulerHeight, this.rulerWidth / 2, i + this.rulerHeight], {
                stroke: this.rulerBorderColor,
                strokeWidth: 1,
                selectable: false,
                evented: false,
                excludeFromExport: true
            });

            if (i % 50 === 0) {
                mark.set({
                    strokeWidth: 2,
                    width: this.rulerWidth
                });

                const text = new fabric.Text(i.toString(), {
                    left: 2,
                    top: i + this.rulerHeight + 2,
                    fontSize: this.rulerFontSize,
                    fill: this.rulerTextColor,
                    angle: -90,
                    selectable: false,
                    evented: false,
                    excludeFromExport: true
                });

                this.canvas.add(text);
            }

            this.canvas.add(mark);
        }
    }

    /**
     * 绘制标尺
     */
    _drawRulers() {
        if (!this.canvas) return;

        this.canvas.add(this.rulers.horizontal);
        this.canvas.add(this.rulers.vertical);
        this._createRulerMarks();
    }

    /**
     * 清除标尺
     */
    _clearRulers() {
        if (!this.canvas) return;

        this.canvas.remove(this.rulers.horizontal);
        this.canvas.remove(this.rulers.vertical);

        // 清除刻度
        this.canvas.getObjects().forEach(obj => {
            if (obj.excludeFromExport && !obj.isGuide) {
                this.canvas.remove(obj);
            }
        });
    }

    /**
     * 绘制参考线
     */
    _drawGuides() {
        if (!this.canvas) return;

        [...this.guides.horizontal, ...this.guides.vertical].forEach(guide => {
            this.canvas.add(guide);
        });
    }

    /**
     * 清除参考线
     */
    _clearGuides() {
        if (!this.canvas) return;

        [...this.guides.horizontal, ...this.guides.vertical].forEach(guide => {
            this.canvas.remove(guide);
        });
    }

    /**
     * 设置参考线事件
     */
    _setupGuideEvents() {
        if (!this.canvas) return;

        // 从标尺创建参考线
        this.canvas.on('mouse:down', (e) => {
            if (!this.showRuler || !this.showGuides) return;

            const pointer = this.canvas.getPointer(e.e);

            // 从水平标尺创建垂直参考线
            if (pointer.y <= this.rulerHeight) {
                this.addVerticalGuide(pointer.x);
            }

            // 从垂直标尺创建水平参考线
            if (pointer.x <= this.rulerWidth) {
                this.addHorizontalGuide(pointer.y);
            }
        });

        // 参考线对齐
        this.canvas.on('object:moving', (e) => {
            if (!this.showGuides) return;

            const obj = e.target;
            if (obj.isGuide) return;

            const objBounds = obj.getBoundingRect();
            const threshold = 5;

            // 水平参考线对齐
            this.guides.horizontal.forEach(guide => {
                const guideY = guide.top;

                // 对齐对象的顶部、中心和底部
                if (Math.abs(objBounds.top - guideY) < threshold) {
                    obj.set('top', guideY);
                } else if (Math.abs(objBounds.top + objBounds.height / 2 - guideY) < threshold) {
                    obj.set('top', guideY - objBounds.height / 2);
                } else if (Math.abs(objBounds.top + objBounds.height - guideY) < threshold) {
                    obj.set('top', guideY - objBounds.height);
                }
            });

            // 垂直参考线对齐
            this.guides.vertical.forEach(guide => {
                const guideX = guide.left;

                // 对齐对象的左侧、中心和右侧
                if (Math.abs(objBounds.left - guideX) < threshold) {
                    obj.set('left', guideX);
                } else if (Math.abs(objBounds.left + objBounds.width / 2 - guideX) < threshold) {
                    obj.set('left', guideX - objBounds.width / 2);
                } else if (Math.abs(objBounds.left + objBounds.width - guideX) < threshold) {
                    obj.set('left', guideX - objBounds.width);
                }
            });
        });

        // 删除参考线
        this.canvas.on('object:selected', (e) => {
            const obj = e.target;
            if (!obj.isGuide) return;

            // 按Delete键删除参考线
            const handleKeyDown = (e) => {
                if (e.key === 'Delete' || e.key === 'Backspace') {
                    this.canvas.remove(obj);
                    if (obj.lockMovementX) {
                        this.guides.vertical = this.guides.vertical.filter(guide => guide !== obj);
                    } else {
                        this.guides.horizontal = this.guides.horizontal.filter(guide => guide !== obj);
                    }
                    document.removeEventListener('keydown', handleKeyDown);
                }
            };

            document.addEventListener('keydown', handleKeyDown);
        });
    }

    /**
     * 销毁插件
     */
    destroy() {
        if (this.canvas) {
            this._clearRulers();
            this._clearGuides();
            this.guides = {
                horizontal: [],
                vertical: []
            };
            this.rulers = {
                horizontal: null,
                vertical: null
            };
        }
        super.destroy();
    }
} 